package region

import (
	"context"
	"encoding/json"

	"github.com/blog-zero/api/admin/internal/common/errorx"
	"github.com/blog-zero/api/admin/internal/svc"
	"github.com/blog-zero/api/admin/internal/types"
	"github.com/blog-zero/rpc/pub/pubclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListRegionListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListRegionListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListRegionListLogic {
	return &ListRegionListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListRegionListLogic) ListRegionList(req *types.ListRegionReq) (*types.ListRegionResp, error) {
	resp, err := l.svcCtx.PubRegionService.RegionList(l.ctx, &pubclient.RegionListReq{
		Current:  req.Current,
		PageSize: req.PageSize,
	})
	if err != nil {
		reqStr, _ := json.Marshal(req)
		logx.WithContext(l.ctx).Errorf("获取省市区地址信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, errorx.NewDefaultError("获取省市区地址信息失败")
	}

	var list []*types.ListRegionData

	for _, item := range resp.List {
		list = append(list, &types.ListRegionData{
			Id:         item.Id,
			Name:       item.Name,
			ParentCode: item.ParentCode,
			Code:       item.Code,
			Level:      item.Level,
		})
	}

	return &types.ListRegionResp{
		Data:    list,
		Success: true,
		Total:   resp.Total,
		Code:    "000000",
		Message: "获取省市区地址信息成功",
	}, nil
}
